library(survey)
library(dplyr)
library(ggplot2)
library(gridExtra)
library(RColorBrewer)

# Figure 8.9
summary(factor(df$Q11))
summary(factor(df$Q2))
summary(factor(df$Q2A))

df2 <- df[df$Q11 < 77 & !is.na(df$Q2),]
df2 <- df2[df2$Q2 < 77,]

df2a <- df[df$Q11 < 77 & !is.na(df$Q2A),]
df2a <- df2a[df2a$Q2A < 77,]

# Create Survey design
w2_design <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df2
  )

w2_design_1 <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df2a
  )

summary(factor(w2_design$variables$Q2))

Q2_tot <- svytable(~Q2,w2_design)
dod_perc <- data.frame(budget=factor(c("$20 Billion","$55 Billion","$250 Billion",
                                "$450 Billion","$700 Billion",'$1.1 Trillion'), 
                                levels=c("$20 Billion","$55 Billion","$250 Billion",
                                         "$450 Billion","$700 Billion",'$1.1 Trillion')),
                       percent=round(Q2_tot/sum(Q2_tot)*100))

Q2A_tot <- svytable(~Q2A,w2_design_1)
dos_perc <- data.frame(budget=factor(c("$20 Billion","$55 Billion","$250 Billion",
                                "$450 Billion","$700 Billion",'$1.1 Trillion'), 
                       levels=c("$20 Billion","$55 Billion","$250 Billion",
                                "$450 Billion","$700 Billion",'$1.1 Trillion')),
                       percent=round(Q2A_tot/sum(Q2A_tot)*100))



g.dod <- ggplot(dod_perc,aes(x="",y=percent.Freq,fill=budget))+
  geom_bar(stat="identity",width=1,color='white')+
  coord_polar("y",start=0)+
  scale_fill_brewer(palette='Blues')+
  theme_void()+
  geom_text(aes(y=c(95,85,71,53,34,12),label=percent.Freq),color='black',size=4.5)+
  ggtitle("Department of Defense")+
  theme(legend.position = "null",plot.title = element_text(hjust=0.5))
  
g.dos <- ggplot(dos_perc,aes(x="",y=percent.Freq,fill=budget))+
  geom_bar(stat="identity",width=1,color='white')+
  coord_polar("y",start=0)+
  scale_fill_brewer(palette='Blues')+
  theme_void()+
  geom_text(aes(y=c(92,79,63,45,31,13),label=percent.Freq),color='black',size=4.5)+
  ggtitle("Department of State")+
  theme(plot.title = element_text(hjust=0.5))

grid.arrange(g.dod,g.dos,ncol=2,widths=c(1,1.2))
